﻿
var access_token;
window.FB = FBWinJS;
var share = false;

/*Enter your app-id from facebook for your app here.*/
FB.options({
    appId: 'xxxxxxxxxxxxxxxxxxx'
});


(function () {
    "use strict";
    var currentApp = Windows.ApplicationModel.Store.CurrentAppSimulator;
    var page = WinJS.UI.Pages.define("/html/in-app-purchase.html", {
        ready: function (element, options) {

            /*The code in ready function goes into the block of your app.load() function */

            document.getElementById("testProduct1").addEventListener("click", testProduct1, false);
            document.getElementById("product1PurchaseButton").addEventListener("click", purchaseProduct1, false);
            document.getElementById("testProduct2").addEventListener("click", testProduct2, false);
            document.getElementById("product2PurchaseButton").addEventListener("click", purchaseProduct2, false);
            document.getElementById("share2PurchaseButton").addEventListener("click", shareProduct2, false);

            // Initialize the license proxy file
            loadInAppPurchaseProxyFile();
        },
        unload: function () {

            /*The code in unload function goes into the block of your app.unload() function */
            currentApp.licenseInformation.removeEventListener("licensechanged", inAppPurchaseRefreshScenario);
        }
    });

    function loadInAppPurchaseProxyFile() {
        Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync("data").done(
            function (folder) {
                folder.getFileAsync("in-app-purchase.xml").done(
                    function (file) {
                        currentApp.licenseInformation.addEventListener("licensechanged", inAppPurchaseRefreshScenario);
                        Windows.ApplicationModel.Store.CurrentAppSimulator.reloadSimulatorAsync(file).done();
                        // setup product upsell messages
                        currentApp.loadListingInformationAsync().done(
                            function (listing) {
                                var product1 = listing.productListings.lookup("product1");
                                var product2 = listing.productListings.lookup("product2");
                                document.getElementById("product1SellMessage").innerText = "You can buy " + product1.name + " for: " + product1.formattedPrice + ".";
                                document.getElementById("product2SellMessage").innerText = "You can buy " + product2.name + " for: " + product2.formattedPrice + ".";
                            },
                            function () {
                                WinJS.log && WinJS.log("LoadListingInformationAsync API call failed", "sample", "error");
                            });
                    });
            });
    }

    function inAppPurchaseRefreshScenario() {
        var licenseInformation = currentApp.licenseInformation;
        if (licenseInformation.isActive) {
            // license status is active - check the trial status
            if (licenseInformation.isTrial) {
                WinJS.log && WinJS.log("You have only a trial license. You need a full license to make an in-app purchase.", "sample", "error");
            }
        } else {
            WinJS.log && WinJS.log("You don't have active license.", "sample", "error");
        }
    }

    function testProduct1() {
        var licenseInformation = currentApp.licenseInformation;
        if (licenseInformation.productLicenses.lookup("product1").isActive) {
            WinJS.log && WinJS.log("You can use Product 1.", "sample", "status");
        } else {
            WinJS.log && WinJS.log("You don't own Product 1. You must buy Product 1 before you can use it.", "sample", "error");
        }
    }

    function purchaseProduct1() {
        var licenseInformation = currentApp.licenseInformation;
        if (!licenseInformation.productLicenses.lookup("product1").isActive) {
            WinJS.log && WinJS.log("Buying Product 1...", "sample", "status");
            currentApp.requestProductPurchaseAsync("product1").done(
                function () {
                    if (licenseInformation.productLicenses.lookup("product1").isActive) {
                        WinJS.log && WinJS.log("You bought Product 1.", "sample", "status");
                    } else {
                        WinJS.log && WinJS.log("Product 1 was not purchased.", "sample", "status");
                    }
                },
                function () {
                    WinJS.log && WinJS.log("Unable to buy Product 1.", "sample", "error");
                });
        } else {
            WinJS.log && WinJS.log("You already own Product 1.", "sample", "error");
        }
    }

    function testProduct2() {
        var licenseInformation = currentApp.licenseInformation;
        if (licenseInformation.productLicenses.lookup("product2").isActive) {
            WinJS.log && WinJS.log("You can use Product 2.", "sample", "status");
        } else {
            WinJS.log && WinJS.log("You don't own Product 2. You must buy Product 2 before you can use it.", "sample", "error");
        }
    }

    function purchaseProduct2() {
        var licenseInformation = currentApp.licenseInformation;
        if (!licenseInformation.productLicenses.lookup("product2").isActive) {
            WinJS.log && WinJS.log("Buying Product 2...", "sample", "status");
            currentApp.requestProductPurchaseAsync("product2").done(
                function () {
                    if (licenseInformation.productLicenses.lookup("product2").isActive) {
                        WinJS.log && WinJS.log("You bought Product 2.", "sample", "status");
                    } else {
                        WinJS.log && WinJS.log("Product 2 was not purchased.", "sample", "status");
                    }
                },
                function () {
                    WinJS.log && WinJS.log("Unable to buy product 2.", "sample", "error");
                });
        } else {
            WinJS.log && WinJS.log("You already own Product 2.", "sample", "error");
        }
    }



    //fb stuff
    // UTILITIES

    // For logging responses
    function logResponse(response) {
        if (typeof console !== 'undefined')
            console.log('The response was', response);
    }
    
    // AUTHENTICATION
    function loginClicked() {

        if (access_token) {
            postClicked();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins photo_upload share_item', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token){
                        access_token = result.access_token;
                        postClicked();
                    }
                }
            });
        }
    }

    function postClicked() {

        FB.setAccessToken(access_token);

        var body = 'I like this app';
        FB.api('me/feed', 'post', {
            message: body, link: "", caption: "Lets Play TicTac", name: "TicTac", picture: "http://ts2.mm.bing.net/th?id=H.4528524587173721&w=194&h=184&c=7&rs=1&pid=1.7"
        }, function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }
            console.log('Post Id: ' + res.id);
            share = true;

            if (share === true) {
                var licenseInformation = currentApp.licenseInformation;
                if (!licenseInformation.productLicenses.lookup("product2").isActive) {
                    WinJS.log && WinJS.log("Buying Product 2...", "sample", "status");
                    currentApp.requestProductPurchaseAsync("product2").done(
                        function () {
                            if (licenseInformation.productLicenses.lookup("product2").isActive) {
                                WinJS.log && WinJS.log("You bought Product 2 through share", "sample", "status");
                            } else {
                                WinJS.log && WinJS.log("Product 2 was not purchased through share.", "sample", "status");
                            }
                        },
                        function () {
                            WinJS.log && WinJS.log("Unable to buy product 2 through share.", "sample", "error");
                        });
                } else {
                    WinJS.log && WinJS.log("You already own Product 2 .", "sample", "error");
                }
            }
            else {
                WinJS.log && WinJS.log("Unable to get product 2 through share.", "sample", "error");
            }
        });



    }

    function askForPermissions(scope, callback) {

        var redirectUri = 'https://www.facebook.com/connect/login_success.html',
            loginUrl = FB.getLoginUrl({ scope: scope });

        try {

            Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
                Windows.Security.Authentication.Web.WebAuthenticationBroker.default,
                new Windows.Foundation.Uri(loginUrl),
                new Windows.Foundation.Uri(redirectUri))
                .then(function success(result) {
                    if (result.responseStatus == 2) {
                        console.log('error: ' + result.responseerrordetail);
                        callback(new Error(result.responseerrordetail));
                        return;
                    }

                    var parser = document.createElement('a');
                    parser.href = result.responseData;

                    var qs = extractQuerystring(parser.hash.substr(1).split('&'));

                    if (qs.error) {
                        // most likely user clicked don't allow
                        console.log('error: ' + qs.error + ' : ' + qs.error_description);
                        return;
                    }

                    // set it as the default access token.
                    FB.setAccessToken(qs.access_token);

                    callback(null, qs);

                }, function error(err) {
                    console.log('Error Number: ' + err.number);
                    console.log('Error Message: ' + err.message);
                    callback(new Error(err.message));
                });

        } catch (e) {
            // error launching web auth
            console.log(e);
        }
    }

    function extractQuerystring(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    }

    function shareProduct2() {
        loginClicked();        
    }

})();
